package com.feijie.thread_demo.SynchronizedMethodThread;

/**
 * @program: thread_demo
 * @description: 使用synchronized方法确保线程安全
 * @author: 作者
 * @create: 2022-03-07 11:02
 */
public class ThreadSynchronizedMethodSecurity {

    static int tickets = 10;

    class SellTickets implements Runnable{

        @Override
        public void run() {
            //同步方法
            while (tickets > 0) {

                // 调用同步方法
                synMethod();

                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

                if (tickets<=0) {
                    System.out.println(Thread.currentThread().getName()+"--->售票结束");
                }

            }


        }

        synchronized void synMethod() {

/*            if (tickets >=100) {

                return;
            }

            System.out.println(Thread.currentThread().getName()+"---->售出第 "+tickets+" 票 ");
            tickets++ ;*/

            synchronized (this) {
                System.out.println(this.getClass().hashCode());

                if (tickets <=0) {
                    return;
                }

                System.out.println(Thread.currentThread().getName()+"---->售出第 "+tickets+" 票 ");
                tickets-- ;
            }
        }
    }



    public static void main(String[] args) {


//        SellTickets sell = new ThreadSynchronizedMethodSecurity().new SellTickets();
        SellTickets sell1 = new ThreadSynchronizedMethodSecurity().new SellTickets();
        SellTickets sell2 = new ThreadSynchronizedMethodSecurity().new SellTickets();

        Thread thread1 = new Thread(sell1, "1号窗口");
        Thread thread2 = new Thread(sell1, "2号窗口");
        Thread thread3 = new Thread(sell2, "3号窗口");
        Thread thread4 = new Thread(sell2, "4号窗口");

        thread1.start();
        thread2.start();
        thread3.start();
        thread4.start();

    }


}
